# -*- codeing = utf-8 -*-
# @Time: 2022/6/18 1:36
# @Author: Foxhuty
# @File: email_test.py
# @Software: PyCharm
# @Based on python 3.10

from imbox import Imbox
import datetime
import os
import time


def make_directory(f):
    def wrapper(*args, **kwargs):
        if not os.path.exists('D:\\爬虫数据\\招聘'):
            os.makedirs('D:\\爬虫数据\\招聘')
        result = f(*args, **kwargs)
        return result

    return wrapper


@make_directory
def get_accessary(year, month, day):
    start = time.time()
    n = 0
    with Imbox(mail_host, username=sender, password=mail_pass, ssl=True) as imbox:
        all_inbox_messages = imbox.messages(unread=True)
        for uid, message in all_inbox_messages:
            try:
                mail_date = message.parsed_date.date()
                date_filter = datetime.date(year, month, day)
                print(uid, message.subject, mail_date)
                if mail_date >= date_filter:

                    if message.attachments:
                        for attachment in message.attachments:
                            with open(f'D://爬虫数据//招聘//{attachment["filename"]}', mode='wb') as f:
                                f.write(attachment['content'].getvalue())
                                f.close()
                                imbox.mark_seen(uid=uid)
                                n += 1
                                print(f'第{n}个附件：{message.date}:{message.subject}---{attachment["filename"]}---下载完成。。。')
            except:
                pass

    end = time.time()
    time_spent = (end - start) / 60
    print(f'----------邮件接收完毕,共计用时{round(time_spent, 1)}分钟---------------')


if __name__ == '__main__':
    mail_host = 'imap.qq.com'
    mail_pass = 'gdhprdriyijibjfi'
    # mail_pass = 'tensjeayhyelccbe'
    sender = '80708055@qq.com'
    # sender = '1801007676@qq.com'

    get_accessary(2021,12,1)
